package com.example.framelib.rx;

import com.example.framelib.ApiException;
import com.example.framelib.cons.Cons;
import com.google.gson.JsonSyntaxException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeoutException;

import rx.Subscriber;


public abstract class FilterSubscriber<T> extends Subscriber<T> {

    private String errorMsg;
    private int errorCode;

    @Override
    public void onCompleted(){

    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof ApiException) {
            ApiException apiEx = (ApiException) e;
            errorCode = apiEx.getErrorCode();
            errorMsg =apiEx.getErrorMessage();
        } else if (e instanceof TimeoutException || e instanceof SocketTimeoutException
                || e instanceof ConnectException){
            errorCode = Cons.ResponseCons.EX_CODE_OVERTIME;
            errorMsg = "网络异常";
        }else if (e instanceof JsonSyntaxException){
            errorCode = Cons.ResponseCons.EX_CODE_JSON_SYNTAX;
            errorMsg = "Json格式出错了";
            //假如导致这个异常触发的原因是服务器的问题，那么应该让服务器知道，所以可以在这里
            //选择上传原始异常描述信息给服务器
        }else {
            errorCode = Cons.ResponseCons.EX_CODE_OTHER;
            errorMsg = e.getMessage();
        }

        onError(errorCode,errorMsg);

    }

    public abstract void onError(int errorCode,String errorMsg);

}
